import Flutter
import UIKit

public class SwiftFlutterPluginDemoPlugin: NSObject, FlutterPlugin {
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "icu.guodapeng.flutter_plugin_demo", binaryMessenger: registrar.messenger())
        let instance = SwiftFlutterPluginDemoPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)

        let eventChannel = FlutterEventChannel(name: "icu.guodapeng.flutter_plugin_demo/event", binaryMessenger: registrar.messenger())
        eventChannel.setStreamHandler(SwiftStreamHandler())

        registrar.register(FlutterPluginDemoViewFactory(), withId: "platform_text_view")
    }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "getPlatformVersion":
            result("iOS " + UIDevice.current.systemVersion)
        case "testArg":
            let arguments = call.arguments as! [String: Any]
            result("iOS " + (arguments["value"] as! String))
        case "testArgArr":
            let arguments = call.arguments as! [String: Any]
            result(["msg": "iOS " + (arguments["value"] as! String)])
        default:
            result(FlutterMethodNotImplemented)
        }
    }
}

class SwiftStreamHandler: NSObject, FlutterStreamHandler {
    private var eventSink: FlutterEventSink? = nil

    public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        eventSink = events
        NotificationCenter.default.addObserver(
                self,
                selector: #selector(SwiftStreamHandler.voiceChange(_:)),
                name: Notification.Name("AVSystemController_SystemVolumeDidChangeNotification"),
                object: nil
        )
        UIApplication.shared.beginReceivingRemoteControlEvents()
        return nil
    }

    public func onCancel(withArguments arguments: Any?) -> FlutterError? {
        print("flutter_plugin_demo onCancel\n")
        return nil
    }

    @objc func voiceChange(_ notification: Notification) {
        let userInfo = notification.userInfo
        let volume = userInfo?["AVSystemController_AudioVolumeNotificationParameter"] as! Double
        eventSink?(["e": "vol", "v": volume, "t": 3])
    }
}
